package ebj.common.httpclient;

import com.google.common.base.Charsets;
import com.google.common.base.Stopwatch;
import com.google.common.base.Strings;
import com.google.gson.Gson;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.log4j.Logger;

import java.beans.Encoder;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class NetService {
    private static Logger logger = Logger.getLogger(NetService.class);
    
    private static int connTimeout = 5000; // 3s
    private static int socketTimeout = 60000; // 10s

    public static String yeahmobiCallBack(String url) {
        HttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, connTimeout);
        HttpConnectionParams.setSoTimeout(httpParams, socketTimeout);
        DefaultHttpClient client = new DefaultHttpClient(httpParams);
        BufferedReader bReader = null;
        InputStream inStream = null;
        
        HttpGet get = new HttpGet(url);
        HttpResponse response;
        try {
            response = client.execute(get);
            inStream = response.getEntity().getContent();
            bReader = new BufferedReader(new InputStreamReader(inStream));
            StringBuilder strBuilder = new StringBuilder();
            String line;
            while (null != (line = bReader.readLine())) {
                strBuilder.append(line);
            }
            logger.info("Return Msg From BS Yeahmobi: " + strBuilder.toString());
            System.out.println("Return Msg From BS Yeahmobi: " + strBuilder.toString());
            return String.valueOf(response.getStatusLine().getStatusCode());
        } catch (ClientProtocolException e) {
            logger.error("error:", e);
        } catch (IOException e) {
            logger.error("error:", e);
        }

        return "404";
    }
    
    public static String yeahmobiCallBack(String url,String... params) {
        HttpParams httpParams = new BasicHttpParams();
        httpParams.setParameter("report_param", params[0]);
        HttpConnectionParams.setConnectionTimeout(httpParams, connTimeout);
        HttpConnectionParams.setSoTimeout(httpParams, socketTimeout);
        DefaultHttpClient client = new DefaultHttpClient(httpParams);
        BufferedReader bReader = null;
        InputStream inStream = null;
        
        HttpPost post = new HttpPost(url);
        HttpResponse response;
        try {
            response = client.execute(post);
            inStream = response.getEntity().getContent();
            bReader = new BufferedReader(new InputStreamReader(inStream));
            StringBuilder strBuilder = new StringBuilder();
            String line;
            while (null != (line = bReader.readLine())) {
                strBuilder.append(line);
            }
            logger.info("Return Msg From BS Yeahmobi: " + strBuilder.toString());
            return String.valueOf(response.getStatusLine().getStatusCode());
        } catch (ClientProtocolException e) {
            logger.error("error:", e);
        } catch (IOException e) {
            logger.error("error:", e);
        }
        
        return "404";
    }
    
    public static String yeahmobiCallBack2(String url,String params) throws UnsupportedEncodingException {
//        HttpParams httpParams = new BasicHttpParams();
//        HttpConnectionParams.setConnectionTimeout(httpParams, connTimeout);
//        HttpConnectionParams.setSoTimeout(httpParams, socketTimeout);
//        DefaultHttpClient client = new DefaultHttpClient(httpParams);
        DefaultHttpClient client = new DefaultHttpClient();
        BufferedReader bReader = null;
        InputStream inStream = null;
        
        HttpPost post = new HttpPost(url);
        HttpResponse response;
        
        
        List<NameValuePair> prms=new ArrayList<NameValuePair>();  
        //建立一个NameValuePair数组，用于存储欲传送的参数  
        prms.add(new BasicNameValuePair("report_param", params));  
        //添加参数  
        post.setEntity(new UrlEncodedFormEntity(prms, HTTP.UTF_8));
        
        try {
            response = client.execute(post);
            inStream = response.getEntity().getContent();
            bReader = new BufferedReader(new InputStreamReader(inStream));
            StringBuilder strBuilder = new StringBuilder();
            String line;
            while (null != (line = bReader.readLine())) {
                strBuilder.append(line);
            }
            logger.info("Return Msg From BS Yeahmobi: " + strBuilder.toString());
            return String.valueOf(response.getStatusLine().getStatusCode());
        } catch (ClientProtocolException e) {
            logger.error("error:", e);
        } catch (IOException e) {
            logger.error("error:", e);
        }
        
        return "404";
    }
    
    
    public static void main(String[] args) throws UnsupportedEncodingException {
        //System.out.println(yeahmobiCallBack3(url, parameter));
        
        String tmp = URLEncoder.encode(param1,"UTF-8");
        System.out.println(yeahmobiCallBack(url + tmp));
        System.out.println(yeahmobiCallBack(url + URLEncoder.encode(param1,"UTF-8")));
    }
    
    // public static String url = "http://report.yeahmobi.com/conv";
    // public static String url = "http://127.0.0.1:8080/datasystem-realquery/report";
    // public static String url = "http://127.0.0.1:9099/report?report_param=";
    public static String url = "http://127.0.0.1:8080/datasystem-realquery/report?report_param=";
    static String parameter = "dataddd1";
    //static String parameter = "{\"settings\":{\"report_id\":\"8412b4adf34ae00d9559e212c72ce57c\",\"return_format\":\"json\",\"data_source\":\"ymds_druid_datasource\",\"time\":{\"start\":1401321600,\"end\":1401408000,\"timezone\":0},\"pagination\":{\"size\":50,\"page\":0}},\"group\":[\"click_time\",\"conv_time\",\"time_diff\",\"aff_id\",\"aff_sub1\",\"offer_id\",\"transaction_id\",\"country\",\"conv_ip\",\"click_ip\"],\"data\":[\"cr\"],\"filters\":{\"$and\":{\"aff_manager\":{\"$in\":[\"31\"]}}}}";
    private static String paramName = "data";
    
    static String urlString = "http://127.0.0.1:8080/datasystem-realquery/report?report_param={%22settings%22:{%22report_id%22:%228412b4adf34ae00d9559e212c72ce57c%22,%22return_format%22:%22json%22,%22data_source%22:%22ymds_druid_datasource%22,%22time%22:{%22start%22:1401321600,%22end%22:1401408000,%22timezone%22:0},%22pagination%22:{%22size%22:50,%22page%22:0}},%22group%22:[%22click_time%22,%22conv_time%22,%22time_diff%22,%22aff_id%22,%22aff_sub1%22,%22offer_id%22,%22transaction_id%22,%22country%22,%22conv_ip%22,%22click_ip%22],%22data%22:[%22cr%22],%22filters%22:{%22$and%22:{%22aff_manager%22:{%22$in%22:[%2231%22]}}}}";
    static String uri = "http://127.0.0.1:8080/datasystem-realquery/report";
    static String param1 = "{\"settings\":{\"report_id\":\"8412b4adf34ae00d9559e212c72ce57c\",\"return_format\":\"json\",\"data_source\":\"ymds_druid_datasource\",\"time\":{\"start\":1401321600,\"end\":1401408000,\"timezone\":0},\"pagination\":{\"size\":50,\"page\":0}},\"group\":[\"click_time\",\"conv_time\",\"time_diff\",\"aff_id\",\"aff_sub1\",\"offer_id\",\"transaction_id\",\"country\",\"conv_ip\",\"click_ip\"],\"data\":[\"cr\"],\"filters\":{\"$and\":{\"aff_manager\":{\"$in\":[\"31\"]}}}}";
    static String url2 = "http://127.0.0.1:8080/datasystem-realquery/report?report_param={\"settings\":{\"report_id\":\"8412b4adf34ae00d9559e212c72ce57c\",\"return_format\":\"json\",\"data_source\":\"ymds_druid_datasource\",\"time\":{\"start\":1401321600,\"end\":1401408000,\"timezone\":0},\"pagination\":{\"size\":50,\"page\":0}},\"group\":[\"click_time\",\"conv_time\",\"time_diff\",\"aff_id\",\"aff_sub1\",\"offer_id\",\"transaction_id\",\"country\",\"conv_ip\",\"click_ip\"],\"data\":[\"cr\"],\"filters\":{\"$and\":{\"aff_manager\":{\"$in\":[\"31\"]}}}}";
    
    
    public static Integer yeahmobiCallBack3(String url, String jsonParam) throws UnsupportedEncodingException {
        DefaultHttpClient client = new DefaultHttpClient();
        boolean res = false;
        int statusCode = 404;
        Stopwatch stopwatch = Stopwatch.createStarted();
        try {
            HttpPost httpPost = new HttpPost(url);

            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair(paramName, jsonParam));
            httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
            HttpResponse response = client.execute(httpPost);
            statusCode = response.getStatusLine().getStatusCode();
        } catch (UnsupportedEncodingException e) {
            logger.error("", e);
        } catch (IOException e) {
            logger.error("", e);
        } catch (IllegalStateException e) {
            logger.error("", e);
        } finally {
            client.getConnectionManager().shutdown();
        }

        long mills = stopwatch.elapsed(TimeUnit.MILLISECONDS);
        return statusCode;
    }
    
    public static void yeahMobiCallBack(String url) {
        HttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, connTimeout);
        HttpConnectionParams.setSoTimeout(httpParams, socketTimeout);
        DefaultHttpClient client = new DefaultHttpClient(httpParams);
        BufferedReader bReader = null;
        InputStream inStream = null;
        
        HttpGet get = new HttpGet(url);
        HttpResponse response;
        try {
            response = client.execute(get);
            inStream = response.getEntity().getContent();
            bReader = new BufferedReader(new InputStreamReader(inStream));
            StringBuilder strBuilder = new StringBuilder();
            String line;
            while (null != (line = bReader.readLine())) {
                strBuilder.append(line);
            }
            logger.info("Return Msg From BS Yeahmobi: " + strBuilder.toString());
            String code = String.valueOf(response.getStatusLine().getStatusCode());
            if (!Strings.isNullOrEmpty(code)) {
                if ("200".equals(code)) {
                    logger.info("BS Yeahmobi Api [" + url + "] CallBack Succeed.");
                } else {
                    logger.info("BS Yeahmobi Api [" + url + "] CallBack Returned With Code [" + code + "].");
                }
            } 
        } catch (ClientProtocolException e) {
            logger.error("error:", e);
        } catch (IOException e) {
            logger.error("error:", e);
        }
    }
}
